package nf;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import nf.modular.data.ClassificationResult;
import nf.modular.data.QueueEntry;
import nf.pluginsys.Wiring;

class ClassificationThread implements Runnable {
	private BlockingDeque<QueueEntry> queue = null;
	private ConcurrentHashMap<String, ClassificationResult> results = null;
	private AtomicInteger counter = null;
	private AtomicInteger killCounter = null;
	private volatile static int UID = 1;
	private int myID = 0;
	private Wiring wiring = null;
	private int threadID = -1;
	
	public ClassificationThread(BlockingDeque<QueueEntry> queue, ConcurrentHashMap<String, ClassificationResult> results, 
			AtomicInteger counter, AtomicInteger killCount, Wiring wiring, int TID)
	{
		this.queue = queue;
		this.results = results;
		this.myID = UID++;
		this.counter = counter;
		this.wiring = wiring;
		this.killCounter = killCount;
		this.threadID = TID;
		
	}

	@Override
	public void run() 
	{
		System.out.println("Classification worker thread #" + myID + " started.");
		while(!queue.isEmpty())
		{
			QueueEntry myFile = queue.remove();
			if(myFile == null)
			{
				System.out.println("File is null?");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				continue;
			}
			
			myFile.processed = false;
			myFile.inProgress = true;
			
			MainWindow.instance.asyncUpdate();
			
			ClassificationResult result = wiring.processFile(myFile.file.getAbsolutePath(), threadID);
			
			if(result == null)
			{
				result = new ClassificationResult();
				result.error = true;
				result.type = -1;
				result.typeIcon = null;
				result.typeName = "ERROR";
			}
			
			myFile.processed = true;
			myFile.inProgress = false;
			myFile.result = result;
			
			results.put(myFile.file.getName(), result);
			counter.incrementAndGet();
			
			System.gc();
		}
		
		killCounter.incrementAndGet();
		System.out.println("Worker thread #" + myID + " died, no more jobs to do.");
	}
}
